Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: Reactjs Interview Questions Description: React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.in this notes i have done 300+ interview questions and answers so that is best for interview from my side
Questions Core React What is React? What are the major features of React? What is JSX? What is the difference between Element and Component? How to create components in React? When to use a Class Component over a Function Component? What are Pure Components? What is state in React? What are props in React? What is the difference between state and props? Why should we not update the state directly? What is the purpose of callback function as an argument of setState()? What is the difference between HTML and React event handling? How to bind methods or event handlers in JSX callbacks? How to pass a parameter to an event handler or callback? What are synthetic events in React? What are inline conditional expressions? What is “key” prop and what is the benefit of using it in arrays of elements? What is the use of refs? How to create refs? What are forward refs? 1
No
...
Questions
60 61 62 63 64 65
How to use InnerHtml in React? How to use styles in React? How events are different in React? What will happen if you use setState in constructor? What is the impact of indexes as keys? Is it good to use setState() in componentWillMount() method? What will happen if you use props in initial state? How do you conditionally render components? Why we need to be careful when spreading props on DOM elements?? How you use decorators in React? How do you memoize a component? How you implement Server-Side Rendering or SSR? How to enable production mode in React? What is CRA and its benefits? What is the lifecycle methods order in mounting? What are the lifecycle methods going to be deprecated in React v16? What is the purpose of getDerivedStateFromProps() lifecycle method? What is the purpose of getSnapshotBeforeUpdate() lifecycle method? Do Hooks replace render props and higher order components? What is the recommended way for naming components? What is the recommended ordering of methods in component class? What is a switching component? Why we need to pass a function to setState()? What is strict mode in React? What are React Mixins? Why is isMounted() an anti-pattern and what is the proper solution? What are the Pointer Events supported in React? Why should component names start with capital letter? Are custom DOM attributes supported in React v16? What is the difference between constructor and getInitialState? Can you force a component to re-render without calling setState? What is the difference between super() and super(props) in React using ES6 classes? How to loop inside JSX?
Questions React Router What is React Router? How React Router is different from history library? What are the components of React Router v4? What is the purpose of push and replace methods of history? How do you programmatically navigate using React router v4? How to get query parameters in React Router v4 Why you get “Router may have only one child element” warning? How to pass params to history
...
Questions
162 163 164
How to use connect from React Redux? How to reset state in Redux? Whats the purpose of at symbol in the redux connect decorator? What is the difference between React context and React Redux? Why are Redux state functions called reducers? How to make AJAX request in Redux? Should I keep all component’s state in Redux store? What is the proper way to access Redux store? What is the difference between component and container in React Redux? What is the purpose of the constants in Redux? What are the different ways to write mapDispatchToProps()? What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()? How to structure Redux top level directories? What is redux-saga? What is the mental model of redux-saga? What are the differences between call and put in redux-saga What is Redux Thunk? What are the differences between redux-saga and redux-thunk What is Redux DevTools? What are the features of Redux DevTools? What are Redux selectors and Why to use them? What is Redux Form? What are the main features of Redux Form? How to add multiple middlewares to Redux? How to set initial state in Redux? How Relay is different from Redux? What is an action in Redux? React Native What is the difference between React Native and React? How to test React Native apps? How to do logging in React Native? How to debug your React Native? React supported libraries and Integration What is reselect and how it works? What is Flow? What is the difference between Flow and PropTypes?
No
...
js? What is the difference between React and Angular? Why React tab is not showing up in DevTools? What are styled components? Give an example of Styled Components? What is Relay? How to use TypeScript in create-react-app application? Miscellaneous What are the main features of reselect library? Give an example of reselect usage? Does the statics object work with ES6 classes in React? Can Redux only be used with React? Do you need to have a particular build tool to use Redux? How Redux Form initialValues get updated from state? How React PropTypes allow different type for one prop? Can I import an SVG file as react component? Why are inline ref callbacks or functions not recommended? What is render hijacking in React? What are HOC factory implementations? How to pass numbers to React component? Do I need to keep all my state into Redux? Should I ever use react internal state? What is the purpose of registerServiceWorker in React? What is React memo function? What is React lazy function? How to prevent unnecessary updates using setState? How do you render Array, Strings and Numbers in React 16 Version? How to use class field declarations syntax in React classes? What are hooks? What rules need to be followed for hooks? How to ensure hooks followed the rules in your project? What are the differences between Flux and Redux? What are the benefits of React Router V4? Can you describe about componentDidCatch lifecycle method signature?
What are the conditions to safely use the index as a key? Is it keys should be globally unique? What is the popular choice for form handling? What are the advantages of formik over redux form library? Why do you not required to use inheritance? Can I use web components in react application? What is dynamic import? What are loadable components? What is suspense component? What is route based code splitting? Give an example on How to use context? What is the purpose of default value in context? How do you use contextType? What is a consumer? How do you solve performance corner cases while using context? What is the purpose of forward ref in HOCs? Is it ref argument available for all functions or class components? Why do you need additional care for component libraries while using forward refs? How to create react class components without ES6? Is it possible to use react without JSX? What is diffing algorithm? What are the rules covered by diffing algorithm? When do you need to use refs? Is it prop must be named as render for render props? What are the problems of using render props with pure components? How do you create HOC using render props? What is windowing technique? How do you print falsy values in JSX? What is the typical use case of portals? How do you set default value for uncontrolled component? What is your favorite React stack? What is the difference between Real DOM and Virtual DOM? How to add Bootstrap to a react application? Can you list down top websites or applications using react as front end framework? Is it recommended to use CSS In JS technique in React?
No
...
9? What is the purpose of eslint plugin for hooks? What is the difference between Imperative and Declarative in React? What are the benefits of using typescript with reactjs? How do you make sure that user remains authenticated on page refresh while using Context API State Management? What are the benefits of new JSX transform? How does new JSX transform different from old transform? How do you get redux scaffolding using create-react-app? What are React Server components? What is prop drilling? What is state mutation and how to prevent it? What is the difference between useState and useRef hook?
Core React 1
...
It is used for handling view layer for web and mobile apps
...
React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012
...
What are the major features of React? The major features of React are: • It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive
...
• Follows Unidirectional data flow or data binding
...
� Back to Top 3
...
Basically it just provides syntactic sugar for the React
...
In the example below text inside
tag is returned as JavaScript function to the render function
...
Component { render() { return(
{'Welcome to React world!'}
) } } � Back to Top 4
...
Elements can 11
contain other Elements in their props
...
Once an element is created, it is never mutated
...
createElement( 'div', {id: 'login-btn'}, 'Login' ) The above React
...
render():
Login
Whereas a component can be declared in several different ways
...
In either case, it takes props as an input, and returns a JSX tree as the output: const Button = ({ onLogin }) =>
Login
Then JSX gets transpiled to a React
...
createElement( 'div', { id: 'login-btn', onClick: onLogin }, 'Login' ) � Back to Top 5
...
1
...
Those are pure JavaScript functions that accept props object as the first parameter and return React elements:
12
“jsx harmony function Greeting({ message }) {
{Hello, ${message}‘}
return
} “‘ 2
...
The above function component can be written as: jsx harmony render() { } }
class Greeting extends React
...
props
...
When to use a Class Component over a Function Component? If the component needs state or lifecycle methods then use class component otherwise use function component
...
8 with the addition of Hooks, you could use state , lifecycle methods and other features that were only available in class component right in your function component
...
What are Pure Components? React
...
Component except that it handles the shouldComponentUpdate() method for you
...
Component on the other hand won’t compare current props and state to next out of the box
...
� Back to Top 8
...
We should always try to make our state as simple as possible and minimize the number of stateful components
...
Component { constructor(props) { super(props) this
...
state
...
e
...
� Back to Top 9
...
They are single values or objects containing a set of values that are passed to components on creation using a naming convention similar to HTML-tag attributes
...
14
The primary purpose of props in React is to provide following component functionality: 1
...
2
...
3
...
props
...
For example, let us create an element with reactProp property: jsx harmony
This reactProp (or whatever you came up with) name then becomes a property attached to React’s native props object which originally already exists on all components created using React library
...
reactProp � Back to Top 10
...
While both of them hold information that influences the output of render, they are different in their functionality with respect to component
...
� Back to Top 11
...
//Wrong this
...
message = 'Hello world' Instead use setState() method
...
When state changes, the component responds by rerendering
...
setState({ message: 'Hello World' }) Note: You can directly assign to the state object either in constructor or using latest javascript’s class field declaration syntax
...
What is the purpose of callback function as an argument of setState()? The callback function is invoked when setState finished and the component gets rendered
...
Note: It is recommended to use lifecycle method rather than this callback function
...
log('The name has updated and component re-ren � Back to Top 13
...
In HTML, the event name usually represents in lowercase as a convention:
{'Click
3
...
jsx harmony handleClick() { console
...
handleClick()}>Click Me; } Note: If the callback is passed as prop to child components, those components might do an extra re-rendering
...
bind() or public class fields syntax approach considering performance
...
How to pass a parameter to an event handler or callback? You can use an arrow function to wrap around an event handler and pass parameters:
17
jsx harmony this
...
bind: jsx harmony
...
bind(this, id)} /> Apart from these two approaches, you can also pass arguments to a function which is defined as arrow function jsx harmony onClick={this
...
log("Hello, your ticket number is", id) }; � Back to Top 16
...
Its API is same as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers
...
What are inline conditional expressions? You can use either if statements or ternary expressions which are available from JS to conditionally render expressions
...
jsx harmony
Hello!
{ !isLogin?
unread messages
...
messages
...
length} :
You
}
� Back to Top 18
...
Key prop helps React identify which items have changed, are added, or are removed
...
map((todo) => key={todo
...
text} ) 18
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort: jsx harmony const todoItems = todos
...
text} ) Note: 1
...
This can negatively impact performance and may cause issues with component state
...
If you extract list item as separate component then apply keys on list component instead of li tag
...
There will be a warning message in the console if the key prop is not present on list items
...
What is the use of refs? The ref is used to return a reference to the element
...
� Back to Top 20
...
This is a recently added approach
...
createRef() method and attached to React elements via the ref attribute
...
For example, the search bar component’s input element is accessed as follows, jsx harmony class SearchBar extends Component { constructor(props) { super(props); this
...
state = { term: '' }; this
...
txtSearch = e; } } onInputChange(event) {
19
this
...
txtSearch
...
onInputChange
...
state ref={this
...
Note: You can also use inline ref callbacks even though it is not a recommended approach
...
What are forward refs? Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child
...
forwardRef((props, ref) => ( {props
...
createRef(); {‘Forward Ref’} “‘ � Back to Top 22
...
Because findDOMNode() prevents certain improvements in React in the future
...
scrollIntoView() } render() { return } } The recommended approach is: class MyComponent extends Component { constructor(props){ super(props); this
...
node
...
scrollIntoView(); } render() { return
...
Why are String Refs legacy? If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like ref={'textInput'}, and the DOM node is accessed as this
...
textInput
...
String refs were removed in React v16
...
They force React to keep track of currently executing component
...
2
...
Callback refs are perfectly composable
...
They don’t work with static analysis like Flow
...
refs, as well as its type (which could be different)
...
4
...
g
...
Ref will get attached to DataTable rather than MyComponent: return ; // This would work though! Callback refs are awesome
...
21
What is Virtual DOM? The Virtual DOM (VDOM) is an in-memory representation of Real DOM
...
It’s a step that happens between the render function being called and the displaying of elements on the screen
...
� Back to Top 25
...
1
...
Figure 2: vdom 2
...
3
...
� Back to Top 26
...
The Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs
...
22
Figure 3: vdom2
Figure 4: vdom3
23
What is React Fiber? Fiber is the new reconciliation engine or reimplementation of core algorithm in React v16
...
� Back to Top 28
...
Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames
...
Ability to split interruptible work in chunks
...
Ability to prioritize, rebase and reuse work in progress
...
Ability to yield back and forth between parents and children to support layout in React
...
Ability to return multiple elements from render()
...
Better support for error boundaries
...
What are controlled components? A component that controls the input elements within the forms on subsequent user input is called Controlled Component, i
...
For example, to write all the names in uppercase letters, we use handleChange as below, handleChange(event) { this
...
target
...
toUpperCase()}) } � Back to Top 30
...
This is a bit more like traditional HTML
...
“‘jsx harmony class UserProfile extends React
...
handleSubmit = this
...
bind(this) this
...
createRef() } handleSubmit(event) { alert(‘A name was submitted:’ + this
...
current
...
preventDefault() } render() { return ( {‘Name:’} ); } } “‘ In most cases, it’s recommend to use controlled components to implement forms
...
The alternative is uncontrolled components, where form data is handled by the DOM itself
...
What is the difference between createElement and cloneElement? JSX elements will be transpiled to React
...
Whereas cloneElement is used to clone an element and pass it new props
...
What is Lifting State Up in React? When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor
...
� Back to Top
25
33
...
Mounting: The component is ready to mount in the browser DOM
...
2
...
This phase covers getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods
...
Unmounting: In this last phase, the component is not needed and gets unmounted from the browser DOM
...
It’s worth mentioning that React internally has a concept of phases when applying changes to the DOM
...
Render The component will render without any side effects
...
2
...
3
...
React 16
...
3 � Back to Top 34
...
3 • componentWillMount: Executed before rendering and is used for App level configuration in your root component
...
4+
Figure 6: phases 16
...
• componentWillReceiveProps: Executed when particular prop updates to trigger state transitions
...
By default it returns true
...
It is a great place to improve performance as it allows you to prevent a re-render if component receives new prop
...
• componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes
...
React 16
...
This exists for rare use cases where you need a derived state
...
• componentDidMount: Executed after first rendering and where all AJAX requests, DOM or state updates, and set up event listeners should occur
...
By default, it returns true
...
It is a great place to improve performance as it allows you to prevent a re-render if component receives a new prop
...
Any value returned by this will be passed into componentDidUpdate()
...
e
...
• componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes
...
• componentWillUnmount It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component
...
28
What are Higher-Order Components? A higher-order component (HOC) is a function that takes a component and returns a new component
...
We call them pure components because they can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components
...
2
...
4
...
Render hijacking
...
Props manipulation
...
How to create props proxy for HOC component? You can add/edit props passed to the component using props proxy pattern like this: “‘jsx harmony function HOC(WrappedComponent) { return class Test extends Component { render() { const newProps = { title: ‘New Header’, footer: false, showFeatureX: false, showFeatureY: true } return
...
props} {
...
What is context? Context provides a way to pass data through the component tree without having to pass props down manually at every level
...
const {Provider, Consumer} = React
...
29
What is children prop? Children is a prop (this
...
children) that allows you to pass components as data to other components, just like any other prop you use
...
There are several methods available in the React API to work with this prop
...
Children
...
Children
...
Children
...
Children
...
Children
...
A simple usage of children prop looks as below, “‘jsx harmony const MyDiv = React
...
props
...
render( {‘Hello’} {‘World’} , node ) “‘ � Back to Top 39
...
Single-line comments: jsx harmony
{/* Single-line comments(In vanilla JavaScript, the single-line comments are represented by double slash(//)) */} {`Welcome ${user}, let's play React`}
Multi-line comments: jsx harmony
{/* Multi-line comments for more than one line */} {`Welcome ${user}, let's play React`}
� Back to Top 40
...
The same applies to ES6 sub-classes as well
...
props in your child constructors
...
Component { constructor(props) { super(props) console
...
props) // prints { name: 'John', age: 42 } } } Not passing props: class MyComponent extends React
...
log(this
...
log(props) // prints { name: 'John', age: 42 } } render() { // no difference outside constructor console
...
props) // prints { name: 'John', age: 42 } } } The above code snippets reveals that this
...
It would be the same outside the constructor
...
What is reconciliation? When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one
...
This process is called reconciliation
...
How to set state with a dynamic key name? If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names
...
setState({ [event
...
id]: event
...
value }) } � Back to Top 43
...
jsx harmony render() { // Wrong: handleClick is called instead of passed as a reference! return
...
handleClick}>{'Click Me'} } � Back to Top 44
...
lazy function supports default exports only
...
It also ensures that tree shaking keeps working and don’t pull unused components
...
js export const SomeComponent = /*
...
*/; and reexport MoreComponents
...
js javascript // IntermediateComponent
...
/MoreComponents
...
/IntermediateComponent
...
32
Why React uses className over class attribute? class is a keyword in JavaScript, and JSX is an extension of JavaScript
...
Pass a string as the className prop
...
What are fragments? It’s a common pattern in React which is used for a component to return multiple elements
...
jsx harmony render() { return (
...
Fragment> ) } There is also a shorter syntax, but it’s not supported in many tools: jsx harmony render() { return ( >
<> ) }
� Back to Top 47
...
Fragments are a bit faster and use less memory by not creating an extra DOM node
...
2
...
3
...
� Back to Top 48
...
33
ReactDOM
...
The second argument is a DOM element
...
What are stateless components? If the behaviour is independent of its state then it can be a stateless component
...
But unless you need to use a lifecycle hook in your components, you should go for function components
...
� Back to Top 50
...
These stateful components are always class components and have a state that gets initialized in the constructor
...
state = { count: 0 } } render() { //
...
8 Update: Hooks let you use state and other React features without writing classes
...
How to apply validation on props in React? When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type
...
It’s disabled in production mode due to performance impact
...
We can define propTypes for User component as below: “‘jsx harmony import React from ‘react’ import PropTypes from ‘proptypes’ class User extends React
...
string
...
number
...
props
...
props
...
5 *PropTypes* were moved from `React
...
propTypes = { name: PropTypes
...
isRequired, age: PropTypes
...
isRequired } � Back to Top 52
...
2
...
4
...
JSX makes code easy to read and write
...
Easy to integrate with frameworks (Angular, Backbone) since it is only a view library
...
Easy to write unit and integration tests with tools such as Jest
...
What are the limitations of React? Apart from the advantages, there are few limitations of React too, 1
...
2
...
3
...
4
...
36
5
...
� Back to Top 54
...
A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info) or static getDerivedStateFromError(): “‘jsx harmony class ErrorBoundary extends React
...
state = { hasError: false } } componentDidCatch(error, info) { // You can also log the error to an error reporting service logErrorToMyService(error, info) } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI
...
state
...
’} } return this
...
children }} After that use it as a regular component: ```jsx harmony
� Back to Top 55
...
It has been renamed to componentDidCatch in React v16
...
What are the recommended ways for static type checking? Normally we use PropTypes library (React
...
5) for type checking in the React applications
...
� Back to Top 57
...
Most of the components are not required to use this module
...
� Back to Top 58
...
push(‘/new-location’) }} > {‘Click Me!’} )} /> ) “‘
69
3
...
“‘jsx harmony const Button = (props, context) => ( type=‘button’ onClick={() => { context
...
push(‘/newlocation’) }} > {‘Click Me!’} ) Button
...
PropTypes
...
PropTypes
...
isRequired }) } “‘ � Back to Top 134
...
So the decision has been given to users to choose the implementation they like
...
const queryString = require('query-string'); const parsed = queryString
...
location
...
location
...
get('name') You should use a polyfill for IE11
...
Why you get “Router may have only one child element” warning? You have to wrap your Route’s in a block because is unique in that it renders a route exclusively
...
*/} />
...
70
How to pass params to history
...
props
...
push({ pathname: '/template', search: '?name=sudheer', state: { detail: response
...
� Back to Top 137
...
A with no path always matches
...
How to get history on React Router v4? Below are the list of steps to get history object on React Router v4, 1
...
For example, create history
...
You should use the component instead of built-in routers
...
js inside index
...
/history’ import App from ‘
...
render(( ), holder) “‘
71
3
...
js import history from '
...
push('/go-here') � Back to Top 139
...
Rendering a will navigate to a new location
...
import React, { Component } from 'react' import { Redirect } from 'react-router' export default class LoginComponent extends Component { render() { if (this
...
isLoggedIn === true) { return } else { return
{'Login Please'}
} } }
React Internationalization � Back to Top 140
...
React Intl is part of FormatJS which provides bindings to React via its components and API
...
72
What are the main features of React Intl? Below are the main features of React Intl, 1
...
3
...
5
...
7
...
Display dates and times correctly
...
Pluralize labels in strings
...
Runs in the browser and Node
...
� Back to Top 142
...
Using react components: jsx harmony id={'account'} amount is less than minimum balance
...
Using an API: const messages = defineMessages({ accountMessage: { id: 'account', defaultMessage: 'The amount is less than minimum balance
...
accountMessage) � Back to Top 143
...
/> components from react-intl return elements, not plain text, so they can’t be used for placeholders, alt text, etc
...
You can inject the intl object into your component using injectIntl() higherorder component and then format the message using formatMessage() available on that object
...
formatMessage({id: ‘messageId’}) return } MyComponent
...
isRequired } export default injectIntl(MyComponent) “‘ � Back to Top 144
...
locale}} ) MyComponent
...
isRequired } export default injectIntl(MyComponent) “‘ � Back to Top 145
...
The method is used internally by instances of FormattedDate and it returns the string representation of the formatted date
...
props
...
formatDate(date, { year: ‘numeric’, month: ‘numeric’, day: ‘numeric’ }) const MyComponent = ({intl}) => ( {The formatted date is ${stringDate}} ) MyComponent
...
isRequired } export default injectIntl(MyComponent) “‘
74
React Testing � Back to Top 146
...
It lets you render a component one level deep and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered
...
render() const result = renderer
...
type)
...
props
...
toEqual([
� Back to Top 147
...
This package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a ReactDOM or React Native without using a browser or jsdom
...
create( {‘Facebook’} )
75
console
...
toJSON()) // { // type: ‘a’, // props: { href: ‘https://www
...
com/’ }, // children: [ ‘Facebook’ ] // } “‘ � Back to Top 148
...
� Back to Top 149
...
It’s often used for testing components
...
What are the advantages of Jest over Jasmine? There are couple of advantages compared to Jasmine: • • • •
Automatically finds tests to execute in your source code
...
Allows you to test asynchronous code synchronously
...
• Runs tests in parallel processes so that they finish sooner
...
Give a simple example of Jest test case Let’s write a test for a function that adds two numbers in sum
...
test
...
/sum' test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2))
...
json: { "scripts": { "test": "jest" } } Finally, run yarn test or npm test and Jest will print a result: $ yarn test PASS
...
test
...
What is flux? Flux is an application design paradigm used as a replacement for the more traditional MVC pattern
...
Facebook uses this pattern internally when working with React
...
What is Redux? Redux is a predictable state container for JavaScript apps based on the Flux design pattern
...
It is tiny (about 2kB) and has no dependencies
...
What are the core principles of Redux? Redux follows three fundamental principles: 1
...
The single state tree makes it easier to keep track of changes over time and debug or inspect the application
...
State is read-only: The only way to change the state is to emit an action, an object describing what happened
...
3
...
Reducers are just pure functions that take the previous state and an action as parameters, and return the next state
...
What are the downsides of Redux compared to Flux? Instead of saying downsides we can say that there are few compromises of using Redux over Flux
...
You will need to learn to avoid mutations: Flux is unopinionated about mutating data, but Redux doesn’t like mutations and many packages complementary to Redux assume you never mutate the state
...
js, or instructing your team to write non-mutating code
...
You’re going to have to carefully pick your packages: While Flux explicitly doesn’t try to solve problems such as undo/redo, persistence, or forms, Redux has extension points such as middleware and store enhancers, and it has spawned a rich ecosystem
...
There is no nice Flow integration yet: Flux currently lets you do very impressive static type checks which Redux doesn’t support yet
...
What is the difference mapDispatchToProps()?
between
mapStateToProps()
and
mapStateToProps() is a utility which helps your component get updated state (which is updated by some other components): const mapStateToProps = (state) => { return { todos: getVisibleTodos(state
...
visibilityFilter) } } mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of application state): const mapDispatchToProps = (dispatch) => { return { onTodoClick: (id) => { dispatch(toggleTodo(id)) } } } It is recommended to always use the “object shorthand” form for the mapDispatchToProps
...
const mapDispatchToProps = ({ onTodoClick }) � Back to Top 157
...
Your reducer should be without side effects, simply digesting the action payload and
79
returning a new state object
...
� Back to Top 158
...
Also, it shouldn’t pollute the global window object
...
What are the drawbacks of MVW pattern? 1
...
2
...
3
...
4
...
� Back to Top 160
...
Redux is a tool for managing state throughout the application
...
Think of it as an alternative to (half of) Angular
...
It is usually used as a tool to accomplish asynchronous tasks in JavaScript
...
Redux uses the Reactive paradigm because the Store is reactive
...
RxJS also uses the Reactive paradigm, but instead of being an architecture, it gives you basic building blocks, Observables, to accomplish this pattern
...
How to dispatch an action on load? You can dispatch an action in componentDidMount() method and in render() method you can verify the data
...
props
...
props
...
isLoaded }) const mapDispatchToProps = { fetchData } export default connect(mapStateToProps, mapDispatchToProps)(App) � Back to Top 162
...
Use mapStateToProps(): It maps the state variables from your store to the props that you specify
...
Connect the above props to your container: The object returned by the mapStateToProps function is connected to the container
...
“‘jsx harmony import React from ‘react’ import { connect } from ‘react-redux’ class App extends React
...
props
...
data } }
{
return
{
containerData:
export default connect(mapStateToProps)(App) “‘ � Back to Top 163
...
For example, let us take rootReducer() to return the initial state after USER_LOGOUT action
...
redux-persist keeps a copy of your state in a storage engine
...
const appReducer = combineReducers({ /* your app's top-level reducers */ }) const rootReducer = (state, action) => { if (action
...
keys(state)
...
removeItem(`persist:${key}`) }) state = undefined }
82
return appReducer(state, action) } � Back to Top 164
...
Decorators make it possible to annotate and modify classes and properties at design time
...
• Without decorator: import import import import
React from 'react' * as actionCreators from '
...
todos } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actionCreators, dispatch) } } class MyApp extends React
...
define your main app here } export default connect(mapStateToProps, mapDispatchToProps)(MyApp) • With decorator: import import import import
React from 'react' * as actionCreators from '
...
todos } } function mapDispatchToProps(dispatch) {
83
return { actions: bindActionCreators(actionCreators, dispatch) } } @connect(mapStateToProps, mapDispatchToProps) export default class MyApp extends React
...
define your main app here } The above examples are almost similar except the usage of decorator
...
You can use babel for the decorators support
...
What is the difference between React context and React Redux? You can use Context in your application directly and is going to be great for passing down data to deeply nested components which what it was designed for
...
Also, React Redux uses context internally but it doesn’t expose this fact in the public API
...
Why are Redux state functions called reducers? Reducers always return the accumulation of the state (based on all previous and current actions)
...
Each time a Redux reducer is called, the state and action are passed as parameters
...
You could reduce a collection of actions and an initial state (of the store) on which to perform these actions to get the resulting final state
...
How to make AJAX request in Redux? You can use redux-thunk middleware which allows you to define async actions
...
status === 200) { dispatch(setAccount(response
...
Should I keep all component’s state in Redux store? Keep your data in the Redux store, and the UI related state internally in the component
...
What is the proper way to access Redux store? The best way to access your store in a component is to use the connect() function, that creates a new component that wraps around your existing one
...
This allows you to map state and action creators to your component, and have them passed in automatically as your store updates
...
/actions' import Link from '
...
filter === state
...
filter)) }) const FilterLink = connect( mapStateToProps, mapDispatchToProps )(Link) export default FilterLink Due to it having quite a few performance optimizations and generally being less likely to cause bugs, the Redux developers almost always recommend using connect() over accessing the store directly (using context API)
...
context
...
What is the difference between component and container in React Redux? Component is a class or function component that describes the presentational part of your application
...
Containers subscribe to Redux state updates and dispatch actions, and they usually don’t render DOM elements; they delegate rendering to presentational child components
...
What is the purpose of the constants in Redux? Constants allows you to easily find all usages of that specific functionality across the project when you use an IDE
...
86
Normally we will save them in a single file (constants
...
js)
...
During action creation: Let’s take actions
...
/actionTypes'; export function addTodo(text) { return { type: ADD_TODO, text } } 2
...
js: import { ADD_TODO } from '
...
type) { case ADD_TODO: return [
...
text, completed: false } ]; default: return state } } � Back to Top 172
...
87
Below are the possible options: const mapDispatchToProps = (dispatch) => ({ action: () => dispatch(action()) }) const mapDispatchToProps = (dispatch) => ({ action: bindActionCreators(action, dispatch) }) const mapDispatchToProps = { action } The third option is just a shorthand for the first one
...
What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()? If the ownProps parameter is specified, React Redux will pass the props that were passed to the component into your connect functions
...
/containers/ConnectedComponent’;
The `ownProps` inside your `mapStateToProps()` and `mapDispatchToProps()` functions wil ```javascript { user: 'john' } You can use this object to decide what to return from those functions
...
How to structure Redux top level directories? Most of the applications has several top-level directories as below: 1
...
2
...
3
...
4
...
5
...
This structure works well for small and medium size apps
...
What is redux-saga? redux-saga is a library that aims to make side effects (asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better
...
What is the mental model of redux-saga? Saga is like a separate thread in your application, that’s solely responsible for side effects
...
� Back to Top 177
...
call() function is used to create effect description, which instructs middleware to call the promise
...
Let’s take example of how these effects work for fetching particular user data
...
fetchUser` fu // Instructing middleware to call promise, it resolved value will be assigned to `use const userData = yield call(api
...
userId) // Instructing middleware to dispatch corresponding action
...
What is Redux Thunk? Redux Thunk middleware allows you to write action creators that return a function instead of an action
...
The inner function receives the store methods dispatch() and getState() as parameters
...
What are the differences between redux-saga and redux-thunk? Both Redux Thunk and Redux Saga take care of dealing with side effects
...
Thunk is simple to use and Promises are familiar to many developers, Sagas/Generators are more powerful but you will need to learn them
...
� Back to Top 180
...
If you don’t want to bother with installing Redux DevTools and integrating it into your project, consider using Redux DevTools Extension for Chrome and Firefox
...
What are the features of Redux DevTools? Some of the main features of Redux DevTools are below, 1
...
2
...
3
...
4
...
90
5
...
� Back to Top 182
...
For example, to get user details from the state: const getUserData = state => state
...
data These selectors have two main benefits, 1
...
The selector is not recomputed unless one of its arguments changes � Back to Top 183
...
Redux Form can be used with raw HTML5 inputs, but it also works very well with common UI frameworks like Material UI, React Widgets and React Bootstrap
...
What are the main features of Redux Form? Some of the main features of Redux Form are: 1
...
2
...
3
...
� Back to Top 185
...
91
For example, you can add redux-thunk and logger passing them as arguments to applyMiddleware(): import { createStore, applyMiddleware } from 'redux' const createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore) � Back to Top 186
...
How Relay is different from Redux? Relay is similar to Redux in that they both use a single store
...
Relay caches the data for you and optimizes data fetching for you, by fetching only changed data and nothing more
...
What is an action in Redux? Actions are plain JavaScript objects or payloads of information that send data from your application to your store
...
Actions must have a type property that indicates the type of action being performed
...
What is the difference between React Native and React? React is a JavaScript library, supporting both front end web and being run on the server, for building user interfaces and web applications
...
� Back to Top 189
...
You can run the app in your mobile using expo app (https://expo
...
� Back to Top 190
...
log, console
...
As of React Native v0
...
93
How to debug your React Native? Follow the below steps to debug React Native app: 1
...
2
...
3
...
4
...
5
...
React supported libraries & Integration � Back to Top 192
...
It was originally written to compute derived data from Redux-like applications state, but it can’t be tied to any architecture or library
...
If the the same inputs are provided twice in a row, Reselect returns the cached output
...
� Back to Top 193
...
Flow types can express much more fine-grained distinctions than traditional type systems
...
� Back to Top 194
...
94
PropTypes is a basic type checker (runtime checker) which has been patched onto React
...
If you want more flexible typechecking for your entire project Flow/TypeScript are appropriate choices
...
How to use Font Awesome icons in React? The below steps followed to include Font Awesome in React: 1
...
Import font-awesome in your index
...
min
...
Add Font Awesome classes in className: render() { return
} � Back to Top 196
...
It exists both as a browser extension (for Chrome and Firefox), and as a standalone app (works with other environments including Safari, IE, and React Native)
...
1
...
Firefox extension 3
...
Why is DevTools not loading in Chrome for local files? If you opened a local HTML file in your browser (file://
...
95
� Back to Top 198
...
Create a Polymer element: jsx harmony /> Polymer({ is: 'calender-element', ready: function() { this
...
Create the Polymer component HTML tag by importing it in a HTML document, e
...
import it in the index
...
/src/polymer-components/calender-element
...
Use that element in the JSX file: import React from 'react' class MyComponent extends React
...
What are the advantages of React over Vue
...
js: 1
...
3
...
Gives more flexibility in large apps developing
...
Suitable for mobile apps creating
...
Note: The above list of advantages are purely opinionated and it vary based on the professional experience
...
� Back to Top
96
200
...
React
Angular
React is a library and has only the View layer React handles rendering on the server side
Angular is a framework and has complete MVC functionality AngularJS renders only on the client side but Angular 2 and above renders on the server side Angular follows the template approach for HTML, which makes code shorter and easy to understand Ionic, Angular’s mobile native app is relatively less stable and slower
React uses JSX that looks like HTML in JS which can be confusing React Native, which is a React type to build mobile applications are faster and more stable In React, data flows only in one way and hence debugging is easy
In Angular, data flows both way i
...
But they are helpful as base parameters
...
Why React tab is not showing up in DevTools? When the page loads, React DevTools sets a global named __REACT_DEVTOOLS_GLOBAL_HOOK__, then React communicates with that hook during initialization
...
� Back to Top 202
...
It removes the mapping between styles and components, and lets you write actual CSS augmented with JavaScript
...
Give an example of Styled Components? Lets create and components with specific styles for each
...
h1` font-size: 1
...
section` padding: 4em; background: papayawhip; ` These two variables, Title and Wrapper, are now components that you can render just like any other react component
...
What is Relay? Relay is a JavaScript framework for providing a data layer and client-server communication to web applications using the React view layer
...
How to use TypeScript in create-react-app application? Starting from react-scripts@2
...
0 or higher, there is a built-in support for typescript
...
e, create-react-app now supports typescript natively
...
react-scripts-ts is a set of adjustments to take the standard create-react-app project pipeline and bring TypeScript into the mix
...
gitignore �� images
...
ts �� node_modules/ �� public/ �� src/ � ��
...
json �� tsconfig
...
prod
...
test
...
json
Miscellaneous � Back to Top 206
...
Selectors can compute derived data, allowing Redux to store the minimal possible state
...
Selectors are efficient
...
3
...
They can be used as input to other selectors
...
Give an example of Reselect usage? Let’s take calculations and different amounts of a shipment order with the simplified usage of Reselect:
Can Redux only be used with React? Redux can be used as a data store for any UI layer
...
Redux simply provides a subscription mechanism which can be used by any other code
...
Do you need to have a particular build tool to use Redux? Redux is originally written in ES6 and transpiled for production into ES5 with Webpack and Babel
...
Redux also offers a UMD build that can be used directly without any build process at all
...
101
How Redux Form initialValues get updated from state? You need to add enableReinitialize : true setting
...
� Back to Top 213
...
For example, the height property can be defined with either string or number type as below: Component
...
oneOfType([ PropTypes
...
number ]) } � Back to Top 214
...
This feature is available with react-scripts@2
...
0 and higher
...
/logo
...
� Back to Top 215
...
This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one
...
log("Input Value is: ", this
...
value) }
render () { return (
) } } But our expectation is for the ref callback to get called once, when the component mounts
...
log("Input Value is: ", this
...
value) } setSearchInput = (input) => { this
...
handleSubmit}> type='text' ref={this
...
3, � Back to Top 216
...
It means that you decorate your component by wrapping it into a Higher-Order component
...
It does not actually enable hijacking, but by using HOC you make your component behave differently
...
What are HOC factory implementations? There are two main ways of implementing HOCs in React
...
Props Proxy (PP) and 2
...
But they follow different approaches for manipulating the WrappedComponent
...
We also pass through the props that the HOC receives, hence the name Props Proxy
...
Component { render() { return
...
props}/> } } } Inheritance Inversion In this approach, the returned HOC class (Enhancer) extends the WrappedComponent
...
In this way the relationship between them seems inverse
...
render() } } } � Back to Top 218
...
render(, document
...
Do I need to keep all my state into Redux? Should I ever use react internal state? It is up to the developer’s decision, i
...
, it is developer’s job to determine what kinds of state make up your application, and where each piece of state should live
...
Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component’s internal state
...
Do other parts of the application care about this data? 2
...
Is the same data being used to drive multiple components? 4
...
Do you want to cache the data (i
...
What is the purpose of registerServiceWorker in React? React creates a service worker for you without any configuration by default
...
It’s all about adding offline capabilities to your site
...
/App'; registerServiceWorker from '
...
render(, document
...
What is React memo function? Class components can be restricted from re-rendering when their input props are the same using PureComponent or shouldComponentUpdate
...
memo
...
memo(function MyComponent(props) { /* only rerenders if props change */ }); � Back to Top 222
...
lazy function lets you render a dynamic import as a regular component
...
This must return a Promise which resolves to a module with a default export containing a React component
...
lazy(() => import('
...
lazy and Suspense is not yet available for server-side rendering
...
� Back to Top 223
...
If the values are the same then you need to return null to stop re-rendering otherwise return the latest state value
...
setState(state if (state
...
address; => { === latestAddress) {
latestAddress };
� Back to Top 224
...
You are able to return multiple sibling elements without a wrapping element by returning an array
...
const JSDevs = () => { return (
Brad
Brodge
Brandon
); } Strings and Numbers: You can also return string and number type from the render method
...
How to use class field declarations syntax in React classes? React Class Components can be made much more concise using the class field declarations
...
Let’s take a counter example to demonstrate class field declarations for state without using constructor and methods without binding, class Counter extends Component { state = { value: 0 }; handleIncrement = () => { this
...
value + 1 })); 108
}; handleDecrement = () => { this
...
value - 1 })); }; render() { return (
{this
...
value}
...
handleDecrement}>-
) } } � Back to Top 226
...
8) that lets you use state and other React features without writing a class
...
What rules need to be followed for hooks? You need to follow two rules in order to use hooks, 1
...
i
...
This will ensure that Hooks are called in the same order each time a component renders and it preserves the state of Hooks between multiple useState and useEffect calls
...
Call Hooks from React Functions only
...
e, You shouldn’t call Hooks from regular JavaScript functions
...
How to ensure hooks followed the rules in your project? React team released an ESLint plugin called eslint-plugin-reacthooks that enforces these two rules
...
"react-hooks" ], "rules": { //
...
� Back to Top 229
...
What are the benefits of React Router V4? Below are the main benefits of React Router V4 module, 1
...
A router can be visualized as a single component() which wraps specific child router components()
...
You don’t need to manually set history
...
3
...
Can you describe about componentDidCatch lifecycle method signature? The componentDidCatch lifecycle method is invoked after an error has been thrown by a descendant component
...
error: - The error object which was thrown 2
...
The method structure would be as follows componentDidCatch(error, info) � Back to Top 232
...
Inside Event handlers 2
...
During Server side rendering 4
...
111
Why do you not need error boundaries for event handlers? Error boundaries do not catch errors inside event handlers
...
Unlike the render method and lifecycle methods, the event handlers don’t happen during rendering
...
If you need to catch an error inside an event handler, use the regular JavaScript try / catch statement: class MyComponent extends React
...
state = { error: null }; this
...
handleClick
...
setState({ error }); } } render() { if (this
...
error) { return
Caught an error
...
handleClick}>Click Me } } Note that the above example is demonstrating regular JavaScript behavior and doesn’t use error boundaries
...
What is the difference between try catch block and error boundaries? Try catch block works with imperative code whereas error boundaries are meant for declarative code to render on the screen
...
} Whereas error boundaries wrap declarative code as below,
So if an error occurs in a componentDidUpdate method caused by a setState somewhere deep in the tree, it will still correctly propagate to the closest error boundary
...
What is the behavior of uncaught errors in react 16? In React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree
...
For example, it is worse for a payments app to display a wrong amount than to render nothing
...
What is the proper placement for error boundaries? The granularity of error boundaries usage is up to the developer based on project needs
...
You can wrap top-level route components to display a generic error message for the entire application
...
You can also wrap individual components in an error boundary to protect them from crashing the rest of the application
...
What is the benefit of component stack trace from error boundary? Apart from error messages and javascript stack, React16 will display the component stack trace with file names and line numbers using error boundary concept
...
What is the required method to be defined for a class component? The render() method is the only required method in a class component
...
e, All methods other than render method are optional for a class component
...
What are the possible return types of render method? Below are the list of following types used and return from render method, 1
...
It includes html elements such as and user defined elements
...
Arrays and fragments: Return multiple elements to render as Arrays and Fragments to wrap multiple elements 3
...
4
...
Booleans or null: Doesn’t render anything but these types are used to conditionally render content
...
What is the main purpose of constructor? The constructor is mainly used for two purposes, 1
...
state
114
2
...
setState() here! this
...
handleClick = this
...
bind(this); } � Back to Top 241
...
i
...
� Back to Top 242
...
This is used for undefined props, but not for null props
...
Component { //
...
defaultProps = { color: 'red' }; If props
...
i
...
color will be set to red } Note: If you provide null value then it remains null value
...
115
Why should not call setState in componentWillUnmount? You should not call setState() in componentWillUnmount() because once a component instance is unmounted, it will never be mounted again
...
What is the purpose of getDerivedStateFromError? This lifecycle method is invoked after an error has been thrown by a descendant component
...
The signature of the lifecycle method is as follows, static getDerivedStateFromError(error) Let us take error boundary use case with the above lifecycle method for demonstration purpose, class ErrorBoundary extends React
...
state = { hasError: false }; } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI
...
state
...
; } return this
...
children; } } � Back to Top 245
...
The below methods are called in the following order when a component is being re-rendered
...
1
...
componentDidCatch() � Back to Top 247
...
Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component
...
For example, To ease debugging, choose a display name that communicates that it’s the result of a withSubscription HOC
...
Component {/*
...
displayName = `WithSubscription(${getDisplayName(WrappedComponent)}) return WithSubscription; } function getDisplayName(WrappedComponent) { return WrappedComponent
...
name || 'Component'; } � Back to Top 248
...
If you use es5-shim and es5-sham polyfill then it even support old browsers that doesn’t support ES5 methods
...
What is the purpose of unmountComponentAtNode method? This method is available from react-dom package and it removes a mounted React component from the DOM and clean up its event handlers and state
...
Returns true if a component was unmounted and false if there was no component to unmount
...
unmountComponentAtNode(container) � Back to Top 250
...
The react project supports code splitting via dynamic import() feature
...
js and all its unique dependencies as a separate chunk that only loads after the user clicks the ‘Load’ button
...
js const moduleA = 'Hello'; export { moduleA }; App
...
/moduleA')
...
catch(err => { // Handle failure });
118
}; render() { return (
...
What is the benefit of strict mode? The will be helpful in the below cases 1
...
3
...
5
...
Warning about legacy string ref API usage
...
Detecting legacy context API
...
What are Keyed Fragments? The Fragments declared with the explicit
...
The general use case is mapping a collection to an array of fragments as below, function Glossary(props) { return (
{props
...
map(item => ( // Without the `key`, React will fire a key warning
...
id}>
{item
...
description}
...
In the future, there might be a support for additional attributes, such as event handlers
...
Does React support all HTML attributes? As of React 16, both standard or custom DOM attributes are fully supported
...
Let us take few props with respect to standard HTML attributes,
// Just like node
...
className DOM API // Just like node
...
It also support all SVG attributes
...
What are the limitations with HOCs? Higher-order components come with a few caveats apart from its benefits
...
Don’t use HOCs inside the render method: It is not recommended to apply a HOC to a component within the render method of a component
...
Instead, apply HOCs outside the component definition so that the resulting component is created only once
...
Static methods must be copied over: When you apply a HOC to a component the new component does not have any of the static methods of the original component // Define a static method WrappedComponent
...
*/ } // Now apply a HOC const EnhancedComponent = enhance(WrappedComponent); // The enhanced component has no static method typeof EnhancedComponent
...
Component {/*
...
staticMethod = WrappedComponent
...
Refs aren’t passed through: For HOCs you need to pass through all props to the wrapped component but this does not work for refs
...
In this case you need to use the React
...
How to debug forwardRefs in DevTools? React
...
For example, If you don’t name the render function or not using displayName property then it will appear as ”ForwardRef” in the DevTools, const WrappedComponent = React
...
props} forwardedRef={ref} />; }); But If you name the render function then it will appear as ”ForwardRef(myFunction)” const WrappedComponent = React
...
props} forwardedRef={ref} />;
121
} ); As an alternative, You can also set displayName property for forwardRef function, function logProps(Component) { class LogProps extends React
...
} function forwardRef(props, ref) { return
...
// e
...
"ForwardRef(logProps(MyComponent))" const name = Component
...
name; forwardRef
...
forwardRef(forwardRef); } � Back to Top 256
...
This behavior is available so that it matches the behavior of HTML
...
What is NextJS and major features of it? Next
...
It also provides styling and routing solutions
...
2
...
4
...
6
...
js HTTP server Customizable with your own Babel and Webpack configurations
� Back to Top 258
...
It can be used in child component as below,
...
Is it good to use arrow functions in render methods? Yes, You can use
...
But you need to optimize the performance while using it
...
log('Click happened'); } render() { return this
...
How to prevent a function from being called multiple times? If you use an event handler such as onClick or onScroll and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed
...
Throttling: Changes based on a time based frequency
...
throttle lodash function 2
...
For example, it can be used using _
...
RequestAnimationFrame throttling: Changes based on requestAnimationFrame
...
How JSX prevents Injection Attacks? React DOM escapes any values embedded in JSX before rendering them
...
Everything is converted to a string before being rendered
...
potentiallyMaliciousInput; const element =
{name}
; This way you can prevent XSS(Cross-site-scripting) attacks in the application
...
How do you update rendered elements? You can update UI(represented by rendered element) by passing the newly created element to ReactDOM’s render method
...
toLocaleTimeString()}
...
render(element, document
...
How do you say that props are readonly? When you declare a component as a function or a class, it must never modify its own props
...
Hence, React has a single rule saying “All React components must act like pure functions with respect to their props
...
How do you say that state updates are merged? When you call setState() in the component, React merges the object you provide into the current state
...
state = { posts: [], comments: [] }; } Now you can update them independently with separate setState() calls as below, componentDidMount() { fetchPosts()
...
setState({ posts: response
...
then(response => {
125
this
...
comments }); }); } As mentioned in the above code snippets, this
...
� Back to Top 265
...
This can be achieved through arrow functions or bind method
...
updateUser(userId, e)}>Update User details
...
bind(this, userId)}>Update User details In the both approaches, the synthetic argument e is passed as a second argument
...
� Back to Top 266
...
This way it can conditionally render component
...
loggedIn) { return null; } return (
welcome, {props
...
Component { constructor(props) { super(props); this
...
state
...
state
...
� Back to Top 267
...
1
...
The items in the list have no ids 3
...
� Back to Top 268
...
i
...
For example, the below Book component uses two arrays with different arrays, function Book(props) { const index = (
{props
...
map((page) =>
...
title}
)}
); const content = props
...
map((page) =>
...
title}
{page
...
pageNumber}
); return (
{index} {content}
); } � Back to Top 269
...
In detail, You can categorize them as follows, 1
...
Validation and error messages 3
...
� Back to Top 270
...
The form state is inherently short-term and local, so tracking it in Redux (or any kind of Flux library) is unnecessary
...
Redux-Form calls your entire top-level Redux reducer multiple times ON EVERY SINGLE KEYSTROKE
...
Why are you not required to use inheritance? In React, it is recommended to use composition over inheritance to reuse code between components
...
Whereas, If you want to reuse non-UI functionality between components, it is suggested to extract it into a separate JavaScript module
...
� Back to Top 272
...
Even though many developers won’t use this combination, it may require especially if you are using third-party UI components that are written using Web Components
...
/App
...
129
What is dynamic import? You can achieve code-splitting in your app using dynamic import
...
Normal Import import { add } from '
...
log(add(10, 20)); 2
...
/math")
...
log(math
...
What are loadable components? If you want to do code-splitting in a server rendered app, it is recommend to use Loadable Components because React
...
Loadable lets you render a dynamic import as a regular component
...
/OtherComponent')) function MyComponent() { return (
) } Now OtherComponent will be loaded in a separated bundle � Back to Top 275
...
This can be done using Suspense component
...
lazy(() => import('
...
}>
); } As mentioned in the above code, Suspense is wrapped above the lazy component
...
What is route based code splitting? One of the best place to do code splitting is with routes
...
Due to this, the user experience won’t be disturbed
...
lazy, import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import React, { Suspense, lazy } from 'react'; const Home = lazy(() => import('
...
/routes/About')); const App = () => ( Loading
...
� Back to Top 277
...
For example, in the code below lets manually thread through a “theme” prop in order to style the Button component
...
createContext('luna'); // Create App component where it uses provider to pass theme value in the tree class App extends React
...
Provider value="nova">
...
Component { static contextType = ThemeContext; render() { return
...
132
What is the purpose of default value in context? The defaultValue argument is only used when a component does not have a matching Provider above it in the tree
...
Below code snippet provides default theme value as Luna
...
createContext(defaultValue); � Back to Top 279
...
The contextType property can be used in two ways, 1
...
createContext()
...
context in any of the lifecycle methods and render function
...
Component { componentDidMount() { let value = this
...
context; /*
...
context; /*
...
context; /* render something based on the value of MyContext */ } } MyClass
...
Static field You can use a static class field to initialize your contextType using public class field syntax
...
Component { static contextType = MyContext; render() { let value = this
...
What is a consumer? A Consumer is a React component that subscribes to context changes
...
The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree
...
Consumer> {value => /* render something based on the context value */ }
...
How do you solve performance corner cases while using context? The context uses reference identity to determine when to re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider’s parent re-renders
...
class App extends React
...
Component { constructor(props) { super(props); this
...
state
...
What is the purpose of forward ref in HOCs? Refs will not get passed through because ref is not a prop
...
If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component
...
For example, we can explicitly forward refs to the inner FancyButton component using the React
...
The below HOC logs all props, function logProps(Component) { class LogProps extends React
...
log('old props:', prevProps); console
...
props); } render() { const {forwardedRef,
...
props; // Assign the custom prop "forwardedRef" as a ref return
...
forwardRef((props, ref) => { 135
return
...
Component { focus() { //
...
} export default logProps(FancyButton); Now let’s create a ref and pass it to FancyButton component
...
import FancyButton from '
...
createRef(); ref
...
focus(); label="Click Me" handleClick={handleClick} ref={ref} />; � Back to Top 283
...
The second ref argument only exists when you define a component with React
...
� Back to Top 284
...
This is because your library likely has a different behavior such as what
136
refs get assigned to, and what types are exported
...
� Back to Top 285
...
For default props, you need to define getDefaultProps() as a function on the passed object
...
var Greeting = createReactClass({ getDefaultProps: function() { return { name: 'Jhohn' }; }, getInitialState: function() { return {message: this
...
message}; }, handleClick: function() { console
...
state
...
props
...
i
...
bind(this) with in constructor for event handlers
...
Is it possible to use react without JSX? Yes, JSX is not mandatory for using React
...
Each JSX element is just syntactic sugar for calling React
...
children)
...
Component { render() {
137
return
Hello {this
...
message}
; } } ReactDOM
...
getElementById('root') ); You can write the same code without JSX as below, class Greeting extends React
...
createElement('div', null, `Hello ${this
...
message}`); } } ReactDOM
...
createElement(Greeting, {message: 'World'}, null), document
...
What is diffing algorithm? React needs to use algorithms to find out how to efficiently update the UI to match the most recent tree
...
However, the algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree
...
This is far too expensive
...
Two elements of different types will produce different trees
...
The developer can hint at which child elements may be stable across different renders with a key prop
...
What are the rules covered by diffing algorithm? When diffing two trees, React first compares the two root elements
...
It covers
138
the below rules during reconciliation algorithm, 1
...
For example, elements to , or from to of different types lead a full rebuild
...
DOM Elements Of The Same Type: When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes
...
Component Elements Of The Same Type: When a component updates, the instance stays the same, so that state is maintained across renders
...
After that, the render() method is called and the diff algorithm recurses on the previous result and the new result
...
Recursing On Children: when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference
...
first
second
first
second
third
5
...
When children have keys, React uses the key to match children in the original tree with children in the subsequent tree
...
When do you need to use refs? There are few use cases to go for refs, 1
...
2
...
3
...
� Back to Top 290
...
i
...
Lets take an example with the children prop for render props, (
The mouse position is {mouse
...
y}
)}/> Actually children prop doesn’t need to be named in the list of “attributes” in JSX element
...
x}, {mouse
...
Mouse
...
func
...
What are the problems of using render props with pure components? If you create a function inside a render method, it negates the purpose of pure component
...
You can solve this issue by defining the render function as instance method
...
How do you create HOC using render props? You can implement most higher-order components (HOC) using a regular component with a render prop
...
function withMouse(Component) { return class extends React
...
this
...
� Back to Top 293
...
If your application renders long lists of data then this technique is recommended
...
� Back to Top 294
...
If you still want to display them then you need to convert it to string
...
� Back to Top 295
...
g
...
For example, dialogs, global message notifications, hovercards, and tooltips
...
How do you set default value for uncontrolled component? In React, the value attribute on form elements will override the value in the DOM
...
To handle this case, you can specify a defaultValue attribute instead of value
...
handleSubmit}>